package com.mall.service.authority.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mall.model.domain.UmsAdmin;
import com.mall.model.domain.UmsAdminRoleRelation;
import com.mall.model.domain.UmsRole;
import com.mall.model.vo.PageResult;
import com.mall.service.authority.mapper.UmsAdminRoleRelationMapper;
import com.mall.service.authority.mapper.UmsRoleMapper;
import com.mall.service.authority.service.UmsRoleService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class UmsRoleServiceImpl extends ServiceImpl<UmsRoleMapper, UmsRole> implements UmsRoleService {

    @Autowired
    private UmsAdminRoleRelationMapper umsAdminRoleRelationMapper;

    //根据用户id获得用户角色
    public List<UmsRole> getByAdminId(Integer id) {

        LambdaQueryWrapper<UmsAdminRoleRelation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UmsAdminRoleRelation::getAdminId,id);
        List<UmsAdminRoleRelation> list = umsAdminRoleRelationMapper.selectList(queryWrapper);

        List<Long> roleIds = list.stream().map(item -> {
            return item.getRoleId();
        }).collect(Collectors.toList());

        ArrayList<UmsRole> umsRoles = new ArrayList<>();
        for (Long roleId : roleIds) {
            UmsRole umsRole = this.getById(roleId);
            umsRoles.add(umsRole);
        }

        return umsRoles;
    }

    @Override
    public PageResult getList(Integer pageNum, Integer pageSize, String keyword) {
        Page<UmsRole> umsRolePage = new Page<>(pageNum, pageSize);

        LambdaQueryWrapper<UmsRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(keyword),UmsRole::getName,keyword);
        Page<UmsRole> page = this.page(umsRolePage, queryWrapper);

        return new PageResult(pageNum,pageSize, (int) page.getTotal(),page.getRecords());
    }
}
